package cn.pink.centersrv;

import cn.pink.common.StatService;
import cn.pink.common.support.tools.cache.CacheTool;
import cn.pink.common.support.tools.cache.ICacheListener;
import cn.pink.common.support.tools.cache.RemoveReason;
import cn.pink.core.*;
import cn.pink.common.support.tools.node.NodeTool;
import cn.pink.core.config.CacheConfig;
import cn.pink.core.config.IronConfig;
import io.vertx.core.Promise;

import java.util.List;

/**
 * 中心服节点
 * @Author: pink
 * @Date: 2022/5/19 11:54
 */
public class CenterNode extends Node {
    @Override
    public void start(Promise<Void> startPromise) {
        try {
            port = new CenterPort(String.valueOf(Thread.currentThread().getId()));
            port.startup(this, true);

            CenterService service = new CenterService(port);
            service.startup();
            port.addService(service);

            //启动运行信息统计
            if (IronConfig.STAT_ENABLE) {
                port.addService(new StatService(port));
            }

            registerListener();

            NodeTool.getInstance().registerNode(getId(), port.getId(), NodeType.CENTER).onSuccess(v -> {
                super.start(startPromise);

                CenterPort centerPort = (CenterPort) port;
                centerPort.cacheLoad();
            });

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        super.stop();
    }

    @Override
    public void registerListener() {
        CacheTool.getInstance().registerListener(CacheConfig.NODE, new ICacheListener() {
            @Override
            public void elementAdd(String key, Object value) {

            }

            @Override
            public void elementUpdate(String key, Object value, Object oldValue) {

            }

            @Override
            public void elementRemove(String key, Object oldValue, RemoveReason reason) {
                onRemoveNode((List<NodeInfo>) oldValue);
            }
        });
    }

    @Override
    public void onRemoveNode(List<NodeInfo> nodeInfos) {
        nodeInfos.forEach(nodeInfo -> {
            if(nodeInfo.getNodeType() == NodeType.GAME) {
                CacheTool.getInstance().getCache(CacheConfig.SESSION).values().forEach(v -> {
                    Session session = (Session) v;
                    if(session.getGamePoint().nodeId.equals(nodeInfo.getNodeId())) {
                        CacheTool.getInstance().getCache(CacheConfig.SESSION).remove((String) session.getGamePoint().servId);
                    }
                });
            }
        });
    }
}
